import Vue from 'vue'

import {decrptParam,digitSign,iEncrpt,iEncrptParam,iEncrptParamMap} from '@/base/AesEncrptUtil.js'
import axios from 'axios'
import Storage from '@/base/storage'

import Main from '@/entrys/webadmin/Index.vue'
import router from '@/router/admin/webRouter.js'
import Page404 from '@/entrys/Page404';
import {CONSTVAL} from '@/base/config'
import '@/base/less/reset.css'
import ElementUI from 'element-ui'
import AFTableColumn from 'af-table-column'
import 'element-ui/lib/theme-chalk/index.css';
import '../../assets/css/iconfont.css'
import VueAMap from 'vue-amap';
// import store from '../../store'

//如果需要防止重复点击 请给相应的元素添加样式needsclick 例 class=" needsclick"
import  '@/base/fastclick.js'

FastClick.attach(document.body,{tapDelay:4000})

let page404 = false;


axios.defaults.timeout = 70000;//默认70秒
if(Storage.session.get('token')){
    axios.defaults.headers.tokenid = Storage.session.get('token');
}
let LoadingInstance = null;
axios.interceptors.request.use(
    config => {
        let method = config.method;
        let url = config.url;
        if(method == 'get'){
            if(!config.unLoadFlg){
                LoadingInstance = ElementUI.Loading.service({'text':'加载中','lock':true})
            }
        } else {
            if(!config.data || !config.data.unLoadFlg ) {//如果data中传了unLoadFlg：true 则不展示加载圈，传false或者不传都展示
                LoadingInstance = ElementUI.Loading.service({'text':'加载中','lock':true})
            }
        }
        if(process.env.NODE_ENV === 'development'){
            //开发联调环境需要配置跨域标识
            url = '/apiM' + url;
        }
        let sign = '';
        let operatorId =  Storage.session.get('operatorId');
        //let operatorId = '10022'
        let contentType = config.headers && config.headers.headers&& config.headers.headers['Content-Type'];

        if(method == 'get'){
            if(~url.indexOf('?')){//URL链接中有?，则用&连接
                url += '&';
            }else {
                url += '?';
            }
        } else {
            if(!config.data){
                config.data = {};
            }
        }
        if(!config.data || !config.data.unEncrpt){//如果data中传了unEncrpt：true 则不加密，传false或者不传都默认加密
            if(method == 'get'){
                if(!config.unEncrpt){
                    sign = digitSign(url,method);
                    url = iEncrpt(url);
                }
            }else {
                config.data.operatorId = operatorId;
                sign = digitSign(config.data,method,contentType);//获取数字签名
                config.data = iEncrptParamMap(config.data);
            }
        }
        config.headers.sign = sign;
        config.url = url;
	    return config;
	},
	err => {
	    return Promise.reject(err)
})

// http响应拦截器
axios.interceptors.response.use(res => {
    LoadingInstance && LoadingInstance.close();// 响应成功关闭loading

    try{
        if(~res.config.url.indexOf('/lbs/datacenter/track/h5Download')) {
            return
        } else {
            if(typeof(res.data) != "object"){//不是对象的话就是加密串
                let data = decrptParam(res.data);
                data = JSON.parse(data);
                res.data = data;
            }
        }
    } catch(err){
        console.info('统一解密异常：' + err);
    }
    //鉴权失败状态码9999
    if(res.data.retCode =='9999'){
        ElementUI.MessageBox.alert(res.data.retMsg,'温馨提示')
        .then((action) => {
          Storage.session.remove('token');
          router.push('/login');//回到登录页面
        }).catch(() => {});
    }
    return res;
  }, error => {
    LoadingInstance && LoadingInstance.close();
    if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1){
        if(res.config && res.config.headers && res.config.headers.tokenid){
            ElementUI.MessageBox.alert('服务器忙，请稍候再试！','温馨提示');
        } else {
            return Promise.reject(error);
        }
    }else{
        return Promise.reject(error)
    }
})

const install = function(Vue, config = {}) {
    if (install.installed) return;
    Vue.config.productionTip = false
    Vue.use(ElementUI);
    Vue.use(VueAMap);
    Vue.use(AFTableColumn)
    VueAMap.initAMapApiLoader({
    key: 'ae5a9ecd0762c20b4a4fa4c279202f83',
    plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor','AMap.CitySearch', 'AMap.MouseTool'],
    // 默认高德 sdk 版本为 1.4.4
    v: '1.4.4',
    uiVersion: '1.0'
    });
    Vue.prototype.Loading = ElementUI.Loading;
    Vue.$toast = Vue.prototype.$toast = ElementUI.Notification;

    // 调用 提示框
    Vue.prototype.$messagebox = ElementUI.MessageBox;
    //alert对话框
    Vue.prototype.$alert = (msg,title='温馨提示') =>{
        if(msg && msg.length > 300){
            msg = msg.substr(0,300)
        }
        Vue.prototype.$messagebox.alert(msg,title);
    }
    //异步查询
    Vue.prototype.$http = axios;
    Vue.prototype.CONSTVAL = CONSTVAL;
}
// auto install
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
};

router.beforeEach((to, from, next) => {
    if(to.path != '/login' && !Storage.session.get('operatorId') && to.path != '/forgetPassword'){//跳登录
        //这里判断用户是否登录，验证本地存储是否有token
        Vue.prototype.$message({
            message: "请先登陆",
            type: 'warning'
        });
        next({
            path: '/login'
        })
    }else {
        next();
    }
  })

if(page404){
    new Vue({
        el: '#app',
        router,
        components: { Page404 },
        template: '<Page404/>'
    })
} else {
    new Vue({
        el: '#app',
        router,
        components: { Main },
        template: '<Main/>'
    })

}
